package br.com.amigooo.controller;

import static br.com.caelum.vraptor.view.Results.json;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;


import br.com.amigooo.Session.UserSession;
import br.com.amigooo.model.ReturnMessage;
import br.com.amigooo.model.Role;
import br.com.amigooo.model.User;
import br.com.amigooo.repository.RoleImpl;
import br.com.amigooo.repository.UserImpl;
import br.com.caelum.vraptor.Consumes;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

@Resource
public class LoginController {
    
	private Result result;
    private UserSession userSession;
    private UserImpl userImpl;
    private ReturnMessage returnMessage;
	
    public LoginController(Result result, UserSession userSession) {
        this.result = result;
        this.userSession = userSession;
        this.userImpl = new UserImpl();
    }
    
	@Path("/")
	public void index(){
		
	}

    /**
     * Realiza o login no portal
     * @param userLogin Objeto com dados do usuário
     */
    @Post()
    public void auth(User userLogin) {
        User user = userImpl.getUserAuth(userLogin.getEmail(), userLogin.getUserPassword());

        if (user != null) {
            userSession.setUser(user);

            result.redirectTo(HomeController.class).start();
        } else {
            result.include("error", "<div class=\"alert fade in alert-error error-login\" style='width:80% !important;margin-top: 10px;'>" +
            		"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>" +
            		"Login ou senha incorreta!</div>").redirectTo(this).index();
        }
    }

	/**
	 * Realiza logout
	 */
    @Get()
    public void logout() {
        userSession.logout();
        result.redirectTo(this).index();
    }
    
    /**
     * Realiza login através do dispositivo mobile
     * @param user Objeto com informações do usuário
     */
    @Post
    @Consumes(value="application/json")
	@Path("/mobile/auth")
	public void mobileAuth(User user){
    	User userM = null;
    	
		try{
			userM = this.userImpl.getUserAuth(user.getEmail(),user.getUserPassword());
			
			if(userM != null && userM.getEmail() != null){
				userM = this.userImpl.getUser(user.getEmail());
				
				System.out.println("Usuário logou: " + userM.getName());
				
				result.use(json()).from(userM).serialize();
			}else{
				this.returnMessage = new ReturnMessage("error", "3", null);
				result.use(json()).from(this.returnMessage).serialize();
			}
			
		}catch(RuntimeException e){
			e.printStackTrace();
			this.returnMessage = new ReturnMessage("error", "4", null);
			result.use(json()).from(this.returnMessage).serialize();
		}
	}

    /**
     * Recebe informações do usuário e cria um novo
     * @param user Objeto com usuário retornado do Amigooo mobile
     */
    @Post
    @Consumes(value="application/json")
    @Path("/mobile/register")
    public void mobileRegister(User user){
    	RoleImpl roleImpl = new RoleImpl();
    	UserImpl userImpl = new UserImpl();
    	
    	Role role = roleImpl.getRole("ROLE_USER");
    	Set<Role> lRole = new HashSet<Role>();
    	
    	try {
    		if(user != null && userImpl.getUser(user.getEmail()) == null){
	    		lRole.add(role);
	    		user.setActive(true);
	    		user.setRegistrationDate(new Date());
	    		user.setRating(0);
	    		user.setRole(lRole);
	    		userImpl.save(user);
	    		this.returnMessage = new ReturnMessage(user.getName(), null, "1");
    		}else{
    			this.returnMessage = new ReturnMessage("error", "1", null);
    		}
		} catch (Exception e) {
			e.printStackTrace();
			this.returnMessage = new ReturnMessage("error", "2", null);
		}
    	result.use(json()).from(this.returnMessage).serialize();
    }
}
